

<!DOCTYPE html>
<html lang="zh-CN" data-default-color-scheme=auto>



<head>
  <meta charset="UTF-8">
  <link rel="apple-touch-icon" sizes="76x76" href="/img/favicon.png">
  <link rel="icon" href="/img/favicon.png">
  <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=5.0, shrink-to-fit=no">
  <meta http-equiv="x-ua-compatible" content="ie=edge">
  
  <meta name="theme-color" content="#2f4154">
  <meta name="author" content="Cai Shibo">
  <meta name="keywords" content="cc">
  
    <meta name="description" content="该文章记录对 动态规划 相关题目的分析理解。">
<meta property="og:type" content="article">
<meta property="og:title" content="算法---动态规划">
<meta property="og:url" content="https://hahsx_xd.gitee.io/2022/03/21/%E7%AE%97%E6%B3%95--%E5%8A%A8%E6%80%81%E8%A7%84%E5%88%92/index.html">
<meta property="og:site_name" content="🍊CAI SHIBO🥬">
<meta property="og:description" content="该文章记录对 动态规划 相关题目的分析理解。">
<meta property="og:locale" content="zh_CN">
<meta property="article:published_time" content="2022-03-21T09:13:00.000Z">
<meta property="article:modified_time" content="2022-11-29T07:14:46.511Z">
<meta property="article:author" content="Cai Shibo">
<meta property="article:tag" content="动态规划">
<meta name="twitter:card" content="summary_large_image">
  
  
  <title>算法---动态规划 - 🍊CAI SHIBO🥬</title>

  <link  rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4/dist/css/bootstrap.min.css" />


  <link  rel="stylesheet" href="https://cdn.jsdelivr.net/npm/github-markdown-css@4/github-markdown.min.css" />
  <link  rel="stylesheet" href="https://cdn.jsdelivr.net/npm/hint.css@2/hint.min.css" />

  
    
    
      
      <link  rel="stylesheet" href="https://cdn.jsdelivr.net/npm/highlight.js@10/styles/github-gist.min.css" />
    
  

  
    <link  rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@3/dist/jquery.fancybox.min.css" />
  


<!-- 主题依赖的图标库，不要自行修改 -->

<link rel="stylesheet" href="//at.alicdn.com/t/font_1749284_ba1fz6golrf.css">



<link rel="stylesheet" href="//at.alicdn.com/t/font_1736178_lbnruvf0jn.css">


<link  rel="stylesheet" href="/css/main.css" />

<!-- 自定义样式保持在最底部 -->


  <script id="fluid-configs">
    var Fluid = window.Fluid || {};
    var CONFIG = {"hostname":"hahsx_xd.gitee.io","root":"/","version":"1.8.14","typing":{"enable":true,"typeSpeed":70,"cursorChar":".|","loop":false},"anchorjs":{"enable":true,"element":"h1,h2,h3,h4,h5,h6","placement":"right","visible":"hover","icon":"#"},"progressbar":{"enable":true,"height_px":3,"color":"#29d","options":{"showSpinner":false,"trickleSpeed":100}},"copy_btn":true,"image_zoom":{"enable":true,"img_url_replace":["",""]},"toc":{"enable":true,"headingSelector":"h1,h2,h3,h4,h5,h6","collapseDepth":5},"lazyload":{"enable":true,"loading_img":"/img/loading.gif","onlypost":true,"offset_factor":2},"web_analytics":{"enable":false,"baidu":null,"google":null,"gtag":null,"tencent":{"sid":null,"cid":null},"woyaola":null,"cnzz":null,"leancloud":{"app_id":null,"app_key":null,"server_url":null,"path":"window.location.pathname","ignore_local":false}},"search_path":"/local-search.xml"};
  </script>
  <script  src="/js/utils.js" ></script>
  <script  src="/js/color-schema.js" ></script>
<meta name="generator" content="Hexo 5.4.0"><link rel="alternate" href="/atom.xml" title="🍊CAI SHIBO🥬" type="application/atom+xml">
</head>


<body>
  <header style="height: 70vh;">
    <nav id="navbar" class="navbar fixed-top  navbar-expand-lg navbar-dark scrolling-navbar">
  <div class="container">
    <a class="navbar-brand" href="/">
      <strong>^_^ 🥬 CC</strong>
    </a>

    <button id="navbar-toggler-btn" class="navbar-toggler" type="button" data-toggle="collapse"
            data-target="#navbarSupportedContent"
            aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
      <div class="animated-icon"><span></span><span></span><span></span></div>
    </button>

    <!-- Collapsible content -->
    <div class="collapse navbar-collapse" id="navbarSupportedContent">
      <ul class="navbar-nav ml-auto text-center">
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/">
                <i class="iconfont icon-home-fill"></i>
                首页
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/archives/">
                <i class="iconfont icon-archive-fill"></i>
                归档
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/categories/">
                <i class="iconfont icon-category-fill"></i>
                分类
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/tags/">
                <i class="iconfont icon-tags-fill"></i>
                标签
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/about/">
                <i class="iconfont icon-user-fill"></i>
                关于
              </a>
            </li>
          
        
        
          <li class="nav-item" id="search-btn">
            <a class="nav-link" target="_self" href="javascript:;" data-toggle="modal" data-target="#modalSearch" aria-label="Search">
              &nbsp;<i class="iconfont icon-search"></i>&nbsp;
            </a>
          </li>
        
        
          <li class="nav-item" id="color-toggle-btn">
            <a class="nav-link" target="_self" href="javascript:;" aria-label="Color Toggle">&nbsp;<i
                class="iconfont icon-dark" id="color-toggle-icon"></i>&nbsp;</a>
          </li>
        
      </ul>
    </div>
  </div>
</nav>

    <div class="banner" id="banner" parallax=true
         style="background: url('/img/default.png') no-repeat center center;
           background-size: cover;">
      <div class="full-bg-img">
        <div class="mask flex-center" style="background-color: rgba(0, 0, 0, 0.3)">
          <div class="page-header text-center fade-in-up">
            <span class="h2" id="subtitle" title="算法---动态规划">
              
            </span>

            
              <div class="mt-3">
  
    <span class="post-meta mr-2">
      <i class="iconfont icon-author" aria-hidden="true"></i>
      Cai Shibo
    </span>
  
  
    <span class="post-meta">
      <i class="iconfont icon-date-fill" aria-hidden="true"></i>
      <time datetime="2022-03-21 17:13" pubdate>
        2022年3月21日 下午
      </time>
    </span>
  
</div>

<div class="mt-1">
  
    <span class="post-meta mr-2">
      <i class="iconfont icon-chart"></i>
      10k 字
    </span>
  

  
    <span class="post-meta mr-2">
      <i class="iconfont icon-clock-fill"></i>
      
      
      52 分钟
    </span>
  

  
  
    
      <!-- 不蒜子统计文章PV -->
      <span id="busuanzi_container_page_pv" style="display: none">
        <i class="iconfont icon-eye" aria-hidden="true"></i>
        <span id="busuanzi_value_page_pv"></span> 次
      </span>
    
  
</div>

            
          </div>

          
        </div>
      </div>
    </div>
  </header>

  <main>
    
      

<div class="container-fluid nopadding-x">
  <div class="row nomargin-x">
    <div class="d-none d-lg-block col-lg-2"></div>
    <div class="col-lg-8 nopadding-x-md">
      <div class="container nopadding-x-md" id="board-ctn">
        <div class="py-5" id="board">
          <article class="post-content mx-auto">
            <!-- SEO header -->
            <h1 style="display: none">算法---动态规划</h1>
            
              <p class="note note-info">
                
                  最后更新：23 天前
                
              </p>
            
            <div class="markdown-body">
              <p><strong>该文章记录对 动态规划 相关题目的分析理解。</strong></p>
<span id="more"></span>

<hr>
<h4 id="JZ42-连续子数组的最大和-E"><a href="#JZ42-连续子数组的最大和-E" class="headerlink" title="JZ42 连续子数组的最大和 E"></a>JZ42 连续子数组的最大和 E</h4><p>描述：输入一个长度为n的整型数组array，数组中的一个或连续多个整数组成一个子数组，子数组最小长度为1。求所有子数组的和的最大值。 </p>
<p>解：动态规划。设动态规划列表 dp，dp[i] 代表以元素 array[i] 为结尾的连续子数组最大和；<br>**状态转移方程： dp[i] = Math.max(dp[i-1]+array[i], array[i])**。  </p>
<p>具体思路如下：</p>
<ol>
<li>遍历数组，比较 dp[i-1] + array[i] 和 array[i]的大小;</li>
<li>为了保证子数组的和最大，每次比较 max 都取两者的最大值;</li>
<li>用max变量记录计算过程中产生的最大的连续和dp[i]。</li>
</ol>
<figure class="highlight java"><table><tr><td class="gutter hljs"><div class="hljs code-wrapper"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></div></td><td class="code"><div class="hljs code-wrapper"><pre><code class="hljs java"><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Solution</span> </span>&#123;<br>    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">int</span> <span class="hljs-title">FindGreatestSumOfSubArray</span><span class="hljs-params">(<span class="hljs-keyword">int</span>[] array)</span> </span>&#123;<br>        <span class="hljs-keyword">int</span>[] dp = <span class="hljs-keyword">new</span> <span class="hljs-keyword">int</span>[array.length];<br>        dp[<span class="hljs-number">0</span>] = array[<span class="hljs-number">0</span>];<br>        <span class="hljs-keyword">int</span> max = dp[<span class="hljs-number">0</span>];<br>        <span class="hljs-keyword">for</span> (<span class="hljs-keyword">int</span> i = <span class="hljs-number">1</span>; i &lt; array.length; ++i) &#123;<br>            dp[i] = Math.max(dp[i - <span class="hljs-number">1</span>] + array[i], array[i]);<br>            <span class="hljs-keyword">if</span>(dp[i] &gt; max) &#123;<br>                max = dp[i];<br>            &#125;<br>        &#125;<br>        <span class="hljs-keyword">return</span> max;<br>    &#125;<br>&#125;<br></code></pre></div></td></tr></table></figure>
<p><strong>优化</strong>：上述代码时间复杂度 O(n)，空间复杂度O(n)。本题不用记录dp[i]，因此引入 sum 记录dp[i-1]即可。时间复杂度O(n)，空间复杂度O(1);</p>
<figure class="highlight java"><table><tr><td class="gutter hljs"><div class="hljs code-wrapper"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></div></td><td class="code"><div class="hljs code-wrapper"><pre><code class="hljs java"><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Solution</span> </span>&#123;<br>    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">int</span> <span class="hljs-title">FindGreatestSumOfSubArray</span><span class="hljs-params">(<span class="hljs-keyword">int</span>[] array)</span> </span>&#123;<br>        <span class="hljs-keyword">int</span> max = array[<span class="hljs-number">0</span>], sum = array[<span class="hljs-number">0</span>];<br>        <span class="hljs-keyword">for</span> (<span class="hljs-keyword">int</span> i = <span class="hljs-number">1</span>; i &lt; array.length; ++i) &#123;<br>            sum = Math.max(sum + array[i], array[i]);<br>            <span class="hljs-keyword">if</span>(sum &gt; max) &#123;<br>                max = sum;<br>            &#125;<br>        &#125;<br>        <span class="hljs-keyword">return</span> max;<br>    &#125;<br>&#125;<br></code></pre></div></td></tr></table></figure>
<hr>
<h4 id="JZ85-连续子数组的最大和（二）M"><a href="#JZ85-连续子数组的最大和（二）M" class="headerlink" title="JZ85 连续子数组的最大和（二）M"></a>JZ85 连续子数组的最大和（二）M</h4><p>描述：输入一个长度为n的整型数组array，数组中的一个或连续多个整数组成一个子数组，找到一个具有最大和的连续子数组。</p>
<p>解：在上题的基础上，本体需要返回最大子数组的序列。动态规划的记录最大子数组和的同时，需要记录最大子数组的开始、结束下标。每次重新定位最大子数组前，判断当前子数组和是否比记录的最大值大或者值相同但更长，如满足条件就更新下标。</p>
<p><strong>优化：</strong>思路同上题优化，当前空间复杂度为O(n)，主要用于数组记录以当前位置为末尾的子数组的最大子数组和。将其改为int跟随记录即可，空间复杂度为O(1)。</p>
<figure class="highlight java"><table><tr><td class="gutter hljs"><div class="hljs code-wrapper"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br></pre></div></td><td class="code"><div class="hljs code-wrapper"><pre><code class="hljs java"><span class="hljs-keyword">import</span> java.util.*;<br><br><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Solution</span> </span>&#123;<br>    <span class="hljs-keyword">public</span> <span class="hljs-keyword">int</span>[] FindGreatestSumOfSubArray (<span class="hljs-keyword">int</span>[] array) &#123;<br>        <span class="hljs-comment">// write code here</span><br>        <span class="hljs-keyword">if</span> (array.length == <span class="hljs-number">0</span>) &#123;<br>            <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> <span class="hljs-keyword">int</span>[<span class="hljs-number">0</span>];<br>        &#125;<br>        <span class="hljs-comment">//记录当前连续数组的开始和结束下标</span><br>        <span class="hljs-keyword">int</span> start = <span class="hljs-number">0</span>, end = <span class="hljs-number">1</span>;<br>        <span class="hljs-comment">//max记录整个数组中最大的子数组和；sum记录以array[i-1]为末尾数组的连续子数组最大和</span><br>        <span class="hljs-keyword">int</span> max = Integer.MIN_VALUE, sum = array[<span class="hljs-number">0</span>];<br>        <span class="hljs-comment">//res记录当前和最大的子数组开始、结束下标</span><br>        <span class="hljs-keyword">int</span> res = <span class="hljs-number">0</span>, ree = <span class="hljs-number">1</span>;<br>        <br>        <span class="hljs-keyword">for</span> (<span class="hljs-keyword">int</span> i = <span class="hljs-number">1</span>; i &lt; array.length; ++i) &#123;<br>            <span class="hljs-keyword">if</span> (array[i] &gt; sum + array[i]) &#123;<br>                sum = array[i];<br>                start = i;<br>                end = i + <span class="hljs-number">1</span>;<br>                <span class="hljs-keyword">if</span> (sum &gt; max || sum == max &amp;&amp; ree - res &lt; end - start) &#123;<br>                    res = start;<br>                    ree = end;<br>                    max = sum;<br>                &#125;<br>            &#125; <span class="hljs-keyword">else</span> &#123;<br>                sum = sum + array[i];<br>                end = i + <span class="hljs-number">1</span>;<br>                <span class="hljs-keyword">if</span> (sum &gt; max || (sum == max &amp;&amp; end - start &gt; ree - res)) &#123;<br>                    res = start;<br>                    ree = end;<br>                    max = sum;<br>                &#125;<br>            &#125;<br>        &#125;<br>        <span class="hljs-keyword">return</span> Arrays.copyOfRange(array, res, ree);<br>    &#125;<br>&#125;<br></code></pre></div></td></tr></table></figure>

<hr>
<h4 id="JZ69-跳台阶-E"><a href="#JZ69-跳台阶-E" class="headerlink" title="JZ69 跳台阶 E"></a>JZ69 跳台阶 E</h4><p>描述：一只青蛙一次可以跳上1级台阶，也可以跳上2级。求该青蛙跳上一个 n 级的台阶总共有多少种跳法（先后次序不同算不同的结果）。</p>
<p>解：最简单的递归，当格子数量为1或0时，返回1；其他情况返回jump(n-1)+jump(n-2)。 **n-1-1 和 n-2是重复计算。时间复杂度为O(2^n)**。</p>
<figure class="highlight java"><table><tr><td class="gutter hljs"><div class="hljs code-wrapper"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></div></td><td class="code"><div class="hljs code-wrapper"><pre><code class="hljs java"><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Solution</span> </span>&#123;<br>    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">int</span> <span class="hljs-title">jumpFloor</span><span class="hljs-params">(<span class="hljs-keyword">int</span> target)</span> </span>&#123;<br>        <span class="hljs-keyword">if</span>(target == <span class="hljs-number">0</span>) &#123;<br>            <span class="hljs-keyword">return</span> <span class="hljs-number">1</span>;<br>        &#125;<br>        <span class="hljs-keyword">if</span>(target == <span class="hljs-number">1</span>) &#123;<br>            <span class="hljs-keyword">return</span> <span class="hljs-number">1</span>;<br>        &#125;<br>        <span class="hljs-keyword">return</span> jumpFloor(target - <span class="hljs-number">1</span>) + jumpFloor(target - <span class="hljs-number">2</span>);<br>    &#125;<br>&#125;<br></code></pre></div></td></tr></table></figure>

<p><strong>优化：</strong>为了使**时间复杂度为O(n)、空间复杂度为O(n)**，使用数组记录，遇到已经计算过的无需重复计算。</p>
<figure class="highlight java"><table><tr><td class="gutter hljs"><div class="hljs code-wrapper"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></div></td><td class="code"><div class="hljs code-wrapper"><pre><code class="hljs java"><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Solution</span> </span>&#123;<br>    <span class="hljs-keyword">int</span> f[<span class="hljs-number">50</span>]&#123;<span class="hljs-number">0</span>&#125;;<br>    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">int</span> <span class="hljs-title">jumpFloor</span><span class="hljs-params">(<span class="hljs-keyword">int</span> number)</span> </span>&#123;<br>        <span class="hljs-keyword">if</span> (number &lt;= <span class="hljs-number">1</span>) &#123;<br>        	<span class="hljs-keyword">return</span> <span class="hljs-number">1</span>;<br>        &#125;<br>        <span class="hljs-keyword">if</span> (f[number] &gt; <span class="hljs-number">0</span>) &#123;<br>        	<span class="hljs-keyword">return</span> f[number];<br>        &#125;<br>        <span class="hljs-keyword">return</span> f[number] = (jumpFloor(number-<span class="hljs-number">1</span>)+jumpFloor(number-<span class="hljs-number">2</span>));<br>    &#125;<br>&#125;<br><br></code></pre></div></td></tr></table></figure>

<p><strong>再优化：</strong>为了使时间复杂度为O(n)、**空间复杂度为O(1)**，f (n) = f (n-1) + f (n-2)，只需三个变量分别记录即可。</p>
<figure class="highlight java"><table><tr><td class="gutter hljs"><div class="hljs code-wrapper"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></div></td><td class="code"><div class="hljs code-wrapper"><pre><code class="hljs java"><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Solution</span> </span>&#123;<br>    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">int</span> <span class="hljs-title">jumpFloor</span><span class="hljs-params">(<span class="hljs-keyword">int</span> target)</span> </span>&#123;<br>        <span class="hljs-keyword">int</span> f0 = <span class="hljs-number">1</span>, f1 = <span class="hljs-number">1</span>, f2 = <span class="hljs-number">1</span>;<br>        <span class="hljs-keyword">for</span> (<span class="hljs-keyword">int</span> i = <span class="hljs-number">2</span>; i &lt;= target; ++i) &#123;<br>            f2 = f1 + f0;<br>            f0 = f1;<br>            f1 = f2;<br>        &#125;<br>        <span class="hljs-keyword">return</span> f2;<br>    &#125;<br>&#125;<br></code></pre></div></td></tr></table></figure>

<hr>
<h4 id="JZ71-跳台阶扩展问题-E"><a href="#JZ71-跳台阶扩展问题-E" class="headerlink" title="JZ71 跳台阶扩展问题 E"></a>JZ71 跳台阶扩展问题 E</h4><p>描述：一只青蛙一次可以跳上1级台阶，也可以跳上2级……它也可以跳上n级。求该青蛙跳上一个n级的台阶(n为正整数)总共有多少种跳法。</p>
<p>解：暴力求解<br>f (0) = f (1) = 1 ; f (n) = f (n-1) + f (n-2) + … + f (0) 。 **两层for循环即可。时间复杂度为O(2^n)**。 </p>
<figure class="highlight java"><table><tr><td class="gutter hljs"><div class="hljs code-wrapper"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></div></td><td class="code"><div class="hljs code-wrapper"><pre><code class="hljs java"><span class="hljs-keyword">for</span> (<span class="hljs-keyword">int</span> i=<span class="hljs-number">2</span>; i&lt;=target; ++i) &#123;<br>	<span class="hljs-keyword">for</span> (<span class="hljs-keyword">int</span> j=<span class="hljs-number">0</span>; j&lt;i; ++j) &#123;<br>		f[i] += f[j];<br>	&#125;<br>&#125;<br></code></pre></div></td></tr></table></figure>

<p><strong>优化：</strong><br>f (n) = f (n-1) + f( n-2) + … + f (0)<br>f (n-1) = f (n-2) + … + f (0)<br>所以：f (n) = 2 * f (n-1)  </p>
<figure class="highlight java"><table><tr><td class="gutter hljs"><div class="hljs code-wrapper"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></div></td><td class="code"><div class="hljs code-wrapper"><pre><code class="hljs java"><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Solution</span> </span>&#123;<br>    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">int</span> <span class="hljs-title">jumpFloorII</span><span class="hljs-params">(<span class="hljs-keyword">int</span> target)</span> </span>&#123;<br>        <span class="hljs-keyword">if</span>(target == <span class="hljs-number">1</span> || target == <span class="hljs-number">0</span>) &#123;<br>            <span class="hljs-keyword">return</span> <span class="hljs-number">1</span>;<br>        &#125;<br>        <span class="hljs-keyword">int</span> f0 = <span class="hljs-number">1</span>, f1 = <span class="hljs-number">2</span>;<br>        <span class="hljs-keyword">for</span> (<span class="hljs-keyword">int</span> i = <span class="hljs-number">2</span>; i &lt;= target; i++) &#123;<br>            f0 = f0 * <span class="hljs-number">2</span>;<br>            <br>        &#125;<br>        <span class="hljs-keyword">return</span> f0;<br>    &#125;<br>&#125;<br></code></pre></div></td></tr></table></figure>
<p>或：</p>
<figure class="highlight java"><table><tr><td class="gutter hljs"><div class="hljs code-wrapper"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></div></td><td class="code"><div class="hljs code-wrapper"><pre><code class="hljs java"><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Solution</span> </span>&#123;<br>    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">int</span> <span class="hljs-title">jumpFloorII</span><span class="hljs-params">(<span class="hljs-keyword">int</span> target)</span> </span>&#123;<br>        <span class="hljs-keyword">if</span>(target == <span class="hljs-number">1</span> || target == <span class="hljs-number">0</span>) &#123;<br>            <span class="hljs-keyword">return</span> <span class="hljs-number">1</span>;<br>        &#125;<br>        <span class="hljs-keyword">return</span> (<span class="hljs-keyword">int</span>)Math.pow(<span class="hljs-number">2</span>, target - <span class="hljs-number">1</span>);<br>    &#125;<br>&#125;<br></code></pre></div></td></tr></table></figure>

<h4 id="JZ63-买卖股票的最好时机（一）E"><a href="#JZ63-买卖股票的最好时机（一）E" class="headerlink" title="JZ63 买卖股票的最好时机（一）E"></a>JZ63 买卖股票的最好时机（一）E</h4><p>描述：假设你有一个数组prices，长度为n，其中prices[i]是股票在第i天的价格，请根据这个价格数组，返回买卖股票能获得的最大收益  </p>
<ol>
<li>你可以买入一次股票和卖出一次股票，并非每天都可以买入或卖出一次，总共只能买入和卖出一次，且买入必须在卖出的前面的某一天</li>
<li>如果不能获取到任何利润，请返回0</li>
<li>假设买入卖出均无手续费</li>
</ol>
<p>解：双层循环的暴力求解，时间复杂度为 O(2^n)。</p>
<p><strong>优化：</strong>动态规划、贪心算法，假设第一天买入股票，之后每天都先判断当天售卖股票收益是否最大，再判断当天是否为股票价格新的最低点。</p>
<figure class="highlight java"><table><tr><td class="gutter hljs"><div class="hljs code-wrapper"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></div></td><td class="code"><div class="hljs code-wrapper"><pre><code class="hljs java"><span class="hljs-keyword">import</span> java.util.*;<br><br><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Solution</span> </span>&#123;<br>    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">int</span> <span class="hljs-title">maxProfit</span> <span class="hljs-params">(<span class="hljs-keyword">int</span>[] prices)</span> </span>&#123;<br>        <span class="hljs-comment">// write code here</span><br>        <span class="hljs-keyword">int</span> min = prices[<span class="hljs-number">0</span>], max = <span class="hljs-number">0</span>;<br>        <span class="hljs-keyword">for</span> (<span class="hljs-keyword">int</span> i = <span class="hljs-number">1</span>; i &lt; prices.length; ++i) &#123;<br>            max = Math.max(max, prices[i] - min);<br>            min = Math.min(min, prices[i]);<br>        &#125;<br>        <span class="hljs-keyword">return</span> max;<br>    &#125;<br>&#125;<br></code></pre></div></td></tr></table></figure>
<hr>
<h4 id="JZ70-矩形覆盖-M"><a href="#JZ70-矩形覆盖-M" class="headerlink" title="JZ70 矩形覆盖 M"></a>JZ70 矩形覆盖 M</h4><p>描述：我们可以用 2*1 的小矩形横着或者竖着去覆盖更大的矩形。请问用 n 个 2*1 的小矩形无重叠地覆盖一个 2*n 的大矩形，从同一个方向看总共有多少种不同的方法？</p>
<p>解：<br>2 * 1的矩形，有一种方法；<br>2 * 2的矩形，两个小矩形横放或竖放，有两种方法；<br>2 * 3的矩形，方法总数 = 2 * 2大矩形的方法数（2 * 2的矩形 + 一个竖放的小矩形）+ 2 * 1大矩形的方法数（2 * 1的矩形 + 两个竖放的小矩形；<br><strong>所以，2 * n的矩形方法数 = 2 * n-1的大矩形方法数 + 2 * n-2的大矩形方法数</strong></p>
<figure class="highlight java"><table><tr><td class="gutter hljs"><div class="hljs code-wrapper"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></div></td><td class="code"><div class="hljs code-wrapper"><pre><code class="hljs java"><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Solution</span> </span>&#123;<br>    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">int</span> <span class="hljs-title">rectCover</span><span class="hljs-params">(<span class="hljs-keyword">int</span> target)</span> </span>&#123;<br>        <span class="hljs-keyword">if</span> (target &lt;= <span class="hljs-number">2</span>) &#123;<br>            <span class="hljs-keyword">return</span> target;<br>        &#125;<br>        <span class="hljs-keyword">else</span> &#123;<br>            <span class="hljs-keyword">return</span> rectCover(target - <span class="hljs-number">1</span>) + rectCover(target - <span class="hljs-number">2</span>);<br>        &#125;<br>    &#125;<br>&#125;<br></code></pre></div></td></tr></table></figure>

<hr>
<h4 id="JZ47-礼物的最大价值-M"><a href="#JZ47-礼物的最大价值-M" class="headerlink" title="JZ47 礼物的最大价值 M"></a>JZ47 礼物的最大价值 M</h4><p>描述：在一个m × n的棋盘的每一格都放有一个礼物，每个礼物都有一定的价值（价值大于 0）。你可以从棋盘的左上角开始拿格子里的礼物，并每次向右或者向下移动一格、直到到达棋盘的右下角。给定一个棋盘及其上面的礼物的价值，请计算你最多能拿到多少价值的礼物？</p>
<p>解：动态规划。dp[ i ][ j ] 记录第i行，j列的礼物最大值。因为<strong>第一行、第一列只能横着走、竖着走，因此先赋值</strong>；双层for循环找到所有值。</p>
<figure class="highlight java"><table><tr><td class="gutter hljs"><div class="hljs code-wrapper"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></div></td><td class="code"><div class="hljs code-wrapper"><pre><code class="hljs java"><span class="hljs-keyword">import</span> java.util.*;<br><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Solution</span> </span>&#123;<br>    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">int</span> <span class="hljs-title">maxValue</span> <span class="hljs-params">(<span class="hljs-keyword">int</span>[][] grid)</span> </span>&#123;<br>        <span class="hljs-comment">// write code here</span><br>        <span class="hljs-keyword">int</span>[][] dp = <span class="hljs-keyword">new</span> <span class="hljs-keyword">int</span>[grid.length][grid[<span class="hljs-number">0</span>].length];<br>        dp[<span class="hljs-number">0</span>][<span class="hljs-number">0</span>] = grid[<span class="hljs-number">0</span>][<span class="hljs-number">0</span>];<br>        <span class="hljs-keyword">for</span> (<span class="hljs-keyword">int</span> i = <span class="hljs-number">1</span>; i &lt; grid.length; ++i) &#123;<br>            dp[i][<span class="hljs-number">0</span>] = dp[i - <span class="hljs-number">1</span>][<span class="hljs-number">0</span>] + grid[i][<span class="hljs-number">0</span>];<br>        &#125;<br>        <span class="hljs-keyword">for</span> (<span class="hljs-keyword">int</span> i = <span class="hljs-number">1</span>; i &lt; grid[<span class="hljs-number">0</span>].length; ++i) &#123;<br>            dp[<span class="hljs-number">0</span>][i] = dp[<span class="hljs-number">0</span>][i - <span class="hljs-number">1</span>] + grid[<span class="hljs-number">0</span>][i];<br>        &#125;<br>        <span class="hljs-keyword">for</span> (<span class="hljs-keyword">int</span> i = <span class="hljs-number">1</span>; i &lt; grid.length; ++i) &#123;<br>            <span class="hljs-keyword">for</span> (<span class="hljs-keyword">int</span> j = <span class="hljs-number">1</span>; j &lt; grid[<span class="hljs-number">0</span>].length; ++j) &#123;<br>                dp[i][j] = Math.max(dp[i - <span class="hljs-number">1</span>][j], dp[i][j - <span class="hljs-number">1</span>]) + grid[i][j];<br>            &#125;<br>        &#125;<br>        <span class="hljs-keyword">return</span> dp[grid.length - <span class="hljs-number">1</span>][grid[<span class="hljs-number">0</span>].length - <span class="hljs-number">1</span>];<br>    &#125;<br>&#125;<br></code></pre></div></td></tr></table></figure>

<hr>
<h4 id="JZ48-最长不含重复字符的子字符串-M"><a href="#JZ48-最长不含重复字符的子字符串-M" class="headerlink" title="JZ48 最长不含重复字符的子字符串 M"></a>JZ48 最长不含重复字符的子字符串 M</h4><p>描述：请从字符串中找出一个最长的不包含重复字符的子字符串，计算该最长子字符串的长度。</p>
<p>解：动态规划，重点为<strong>dp[ i ] 表示以i结尾的最长子字符串长度</strong>；使用HashMap记录更新每个字符和其<strong>最晚出现（最大）</strong>的下标；有重复字符出现的情况，还要考虑<strong>以当前重复字符为头尾的子字符串中是否还有重复的字符</strong>。</p>
<figure class="highlight java"><table><tr><td class="gutter hljs"><div class="hljs code-wrapper"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br></pre></div></td><td class="code"><div class="hljs code-wrapper"><pre><code class="hljs java"><span class="hljs-keyword">import</span> java.util.*;<br><br><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Solution</span> </span>&#123;<br>    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">int</span> <span class="hljs-title">lengthOfLongestSubstring</span> <span class="hljs-params">(String s)</span> </span>&#123;<br>        <span class="hljs-comment">// write code here</span><br>        <span class="hljs-keyword">if</span> (s == <span class="hljs-keyword">null</span>) &#123;<br>            <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;<br>        &#125;<br>        <span class="hljs-keyword">if</span> (s.length() &lt;= <span class="hljs-number">1</span>) &#123;<br>            <span class="hljs-keyword">return</span> s.length();<br>        &#125;<br>        <span class="hljs-comment">//记录当前字符串信息，key=字符，value=下标</span><br>        HashMap&lt;Character, Integer&gt; map = <span class="hljs-keyword">new</span> HashMap&lt;&gt;();<br>        <span class="hljs-comment">//记录以i位置为结尾的最长子字符串长度</span><br>        <span class="hljs-keyword">int</span> dp[] = <span class="hljs-keyword">new</span> <span class="hljs-keyword">int</span>[s.length()];<br>        <span class="hljs-keyword">char</span>[] chs = s.toCharArray();<br>        <span class="hljs-keyword">int</span> max = <span class="hljs-number">1</span>;<br>        dp[<span class="hljs-number">0</span>] = <span class="hljs-number">1</span>;<br>        map.put(chs[<span class="hljs-number">0</span>], <span class="hljs-number">0</span>);<br>        <span class="hljs-keyword">for</span> (<span class="hljs-keyword">int</span> i = <span class="hljs-number">1</span>; i &lt; chs.length; ++i) &#123;<br>            <span class="hljs-keyword">if</span> (! map.containsKey(chs[i])) &#123;<br>                dp[i] = dp[i - <span class="hljs-number">1</span>] + <span class="hljs-number">1</span>;<br>            &#125;<br>            <span class="hljs-keyword">else</span> &#123;<br>                <span class="hljs-comment">//如果两个重复字符中间不存在其他重复字符，则长度为i - map.get(chs[i])</span><br>                <span class="hljs-comment">//否则，中间存在其他重复字符串，长度应该更短，为dp[i - 1] + 1</span><br>                dp[i] = Math.min(i - map.get(chs[i]), dp[i - <span class="hljs-number">1</span>] + <span class="hljs-number">1</span>);<br>            &#125;<br>            max = Math.max(max, dp[i]);<br>            <span class="hljs-comment">//添加 或 更新当前字符及下标</span><br>            map.put(chs[i], i);<br>        &#125;<br>        <span class="hljs-keyword">return</span> max;<br>    &#125;<br>&#125;<br></code></pre></div></td></tr></table></figure>

<hr>
<h4 id="JZ46-把数字翻译成字符串-M"><a href="#JZ46-把数字翻译成字符串-M" class="headerlink" title="JZ46 把数字翻译成字符串 M"></a>JZ46 把数字翻译成字符串 M</h4><p>描述：有一种将字母编码成数字的方式：’a-&gt;1’, ‘b-&gt;2’, … , ‘z-&gt;26’。现在给一串数字，返回有多少种可能的译码结果。</p>
<p>解：其实是跳台阶问题的扩展，<strong>dp[ i ] = dp[ i-1 ] + dp [ i-2 ]</strong><br>前提需先进行判断：  </p>
<ol>
<li>判断dp[ 0 ], dp[ 1 ]的值；</li>
<li>当前字符是0，那么其必须和前面的字符组合。若能组合，dp[ i ] = dp；不能组合，直接return 0；</li>
<li>当前字符不是0，不一定要和前面的字符组合。若能组合，dp[ i ] = dp[ i-1 ] + dp [ i-2 ]；不能组合，dp[ i ] = dp[ i-1 ]。</li>
</ol>
<figure class="highlight java"><table><tr><td class="gutter hljs"><div class="hljs code-wrapper"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br></pre></div></td><td class="code"><div class="hljs code-wrapper"><pre><code class="hljs java"><span class="hljs-keyword">import</span> java.util.*;<br><br><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Solution</span> </span>&#123;<br>    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">int</span> <span class="hljs-title">solve</span> <span class="hljs-params">(String nums)</span> </span>&#123;<br>        <span class="hljs-comment">// write code here</span><br>        <span class="hljs-keyword">int</span>[] dp = <span class="hljs-keyword">new</span> <span class="hljs-keyword">int</span>[nums.length()];<br>        <span class="hljs-keyword">char</span>[] chs = nums.toCharArray();<br>        dp[<span class="hljs-number">0</span>] = chs[<span class="hljs-number">0</span>] == <span class="hljs-string">&#x27;0&#x27;</span> ? <span class="hljs-number">0</span> : <span class="hljs-number">1</span>;<br>        <span class="hljs-keyword">if</span> (nums.length() == <span class="hljs-number">1</span>) &#123;<br>            <span class="hljs-keyword">return</span> dp[<span class="hljs-number">0</span>];<br>        &#125;<br>        <span class="hljs-keyword">if</span> (chs[<span class="hljs-number">0</span>] == <span class="hljs-string">&#x27;0&#x27;</span>) &#123;<br>            <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;<br>        &#125; <span class="hljs-keyword">else</span> &#123;<br>            dp[<span class="hljs-number">0</span>] = <span class="hljs-number">1</span>;<br>        &#125;<br>        <br>        <span class="hljs-keyword">if</span> (chs[<span class="hljs-number">1</span>] == <span class="hljs-string">&#x27;0&#x27;</span>) &#123;<br>            <span class="hljs-keyword">if</span> (Integer.parseInt(<span class="hljs-string">&quot;&quot;</span> + chs[<span class="hljs-number">0</span>] + chs[<span class="hljs-number">1</span>]) &gt;= <span class="hljs-number">10</span> &amp;&amp; Integer.parseInt(<span class="hljs-string">&quot;&quot;</span> + chs[<span class="hljs-number">0</span>] + chs[<span class="hljs-number">1</span>]) &lt;= <span class="hljs-number">26</span>) &#123;<br>                dp[<span class="hljs-number">1</span>] = <span class="hljs-number">1</span>;<br>            &#125;<br>            <span class="hljs-keyword">else</span> &#123;<br>                <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;<br>            &#125;<br>        &#125; <span class="hljs-keyword">else</span> &#123;<br>            <span class="hljs-keyword">if</span> (Integer.parseInt(<span class="hljs-string">&quot;&quot;</span> + chs[<span class="hljs-number">0</span>] + chs[<span class="hljs-number">1</span>]) &gt;= <span class="hljs-number">10</span> &amp;&amp; Integer.parseInt(<span class="hljs-string">&quot;&quot;</span> + chs[<span class="hljs-number">0</span>] + chs[<span class="hljs-number">1</span>]) &lt;= <span class="hljs-number">26</span>) &#123;<br>                dp[<span class="hljs-number">1</span>] = <span class="hljs-number">2</span>;<br>            &#125;<br>            <span class="hljs-keyword">else</span> &#123;<br>                dp[<span class="hljs-number">1</span>] = <span class="hljs-number">1</span>;<br>            &#125;<br>        &#125;<br>        <br>        <span class="hljs-keyword">for</span> (<span class="hljs-keyword">int</span> i = <span class="hljs-number">2</span>; i &lt; chs.length; ++i) &#123;<br>            <span class="hljs-keyword">if</span> (chs[i] == <span class="hljs-string">&#x27;0&#x27;</span>) &#123;<br>                <span class="hljs-keyword">if</span> (Integer.parseInt(<span class="hljs-string">&quot;&quot;</span> + chs[i - <span class="hljs-number">1</span>] + chs[i]) &gt;= <span class="hljs-number">10</span> &amp;&amp; Integer.parseInt(<span class="hljs-string">&quot;&quot;</span> + chs[i - <span class="hljs-number">1</span>] + chs[i]) &lt;= <span class="hljs-number">26</span>) &#123;<br>                    dp[i] = dp[i - <span class="hljs-number">2</span>];<br>                &#125;<br>                <span class="hljs-keyword">else</span> &#123;<br>                    <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;<br>                &#125;<br>            &#125;<br>            <span class="hljs-keyword">else</span> &#123;<br>                <span class="hljs-keyword">if</span> (Integer.parseInt(<span class="hljs-string">&quot;&quot;</span> + chs[i - <span class="hljs-number">1</span>] + chs[i]) &gt;= <span class="hljs-number">10</span> &amp;&amp; Integer.parseInt(<span class="hljs-string">&quot;&quot;</span> + chs[i - <span class="hljs-number">1</span>] + chs[i]) &lt;= <span class="hljs-number">26</span>) &#123;<br>                    dp[i] = dp[i - <span class="hljs-number">2</span>] + dp[i - <span class="hljs-number">1</span>];<br>                &#125;<br>                <span class="hljs-keyword">else</span> &#123;<br>                    dp[i] = dp[i - <span class="hljs-number">1</span>];<br>                &#125;<br>            &#125;<br>        &#125;<br>        <span class="hljs-keyword">return</span> dp[chs.length - <span class="hljs-number">1</span>];<br>    &#125;<br>&#125;<br></code></pre></div></td></tr></table></figure>

<p><strong>优化：</strong>优化空间复杂度O( n ) —&gt; O( 1 )，不需要记录所有的dp[ i ]，只需记录当前字符前两个dp的值即可。</p>
<figure class="highlight java"><table><tr><td class="gutter hljs"><div class="hljs code-wrapper"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br></pre></div></td><td class="code"><div class="hljs code-wrapper"><pre><code class="hljs java"><span class="hljs-keyword">import</span> java.util.*;<br><br><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Solution</span> </span>&#123;<br>    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">int</span> <span class="hljs-title">solve</span> <span class="hljs-params">(String nums)</span> </span>&#123;<br>        <span class="hljs-comment">// write code here</span><br>        <span class="hljs-keyword">int</span> first = <span class="hljs-number">1</span>, second = <span class="hljs-number">1</span>;<br>        <span class="hljs-comment">//第一个数字是0直接return 0;</span><br>        <span class="hljs-keyword">if</span> (nums.charAt(<span class="hljs-number">0</span>) == <span class="hljs-string">&#x27;0&#x27;</span>) &#123;<br>            <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;<br>        &#125;<br>        <span class="hljs-comment">//从第2个数字开始</span><br>        <span class="hljs-keyword">for</span> (<span class="hljs-keyword">int</span> i = <span class="hljs-number">1</span>; i &lt; nums.length(); ++i) &#123;<br>            <span class="hljs-comment">//字符是0，要判断能否和前一个字符组合成10-26之间的数</span><br>            <span class="hljs-keyword">if</span> (nums.charAt(i) == <span class="hljs-string">&#x27;0&#x27;</span>) &#123;<br>                <span class="hljs-comment">//能组成dp[i] = dp[i-2]</span><br>                <span class="hljs-keyword">if</span> (Integer.parseInt(nums.substring(i - <span class="hljs-number">1</span>, i + <span class="hljs-number">1</span>)) &gt;= <span class="hljs-number">10</span> &amp;&amp; Integer.parseInt(nums.substring(i - <span class="hljs-number">1</span>, i + <span class="hljs-number">1</span>)) &lt;= <span class="hljs-number">26</span>) &#123;<br>                    <span class="hljs-keyword">int</span> temp = second;<br>                    second = first;<br>                    first = temp;<br>                &#125;<br>                <span class="hljs-comment">//不能组成，直接return 0;</span><br>                <span class="hljs-keyword">else</span> &#123;<br>                    <span class="hljs-keyword">return</span> <span class="hljs-number">0</span>;<br>                &#125;<br>            &#125;<br>            <span class="hljs-comment">//字符不是0，也要判断一下能否组成0-26之间的数</span><br>            <span class="hljs-keyword">else</span> &#123;<br>                <span class="hljs-comment">//能组成，dp[i] = dp[i-1] + dp[i-2]</span><br>                <span class="hljs-keyword">if</span> (Integer.parseInt(nums.substring(i - <span class="hljs-number">1</span>, i + <span class="hljs-number">1</span>)) &gt;= <span class="hljs-number">10</span> &amp;&amp; Integer.parseInt(nums.substring(i - <span class="hljs-number">1</span>, i + <span class="hljs-number">1</span>)) &lt;= <span class="hljs-number">26</span>) &#123;<br>                    second = second + first;<br>                    first = second - first;<br>                &#125;<br>                <span class="hljs-comment">//不能组成，dp[i] = dp[i-1]</span><br>                <span class="hljs-keyword">else</span> &#123;<br>                    first = second;<br>                &#125;<br>            &#125;<br>        &#125;<br>        <span class="hljs-keyword">return</span> second;<br>    &#125;<br>&#125;<br></code></pre></div></td></tr></table></figure>

<hr>
<h4 id="LC11-盛最多水的容器-M"><a href="#LC11-盛最多水的容器-M" class="headerlink" title="LC11 盛最多水的容器 M"></a>LC11 盛最多水的容器 M</h4><p>描述：给定一个长度为 n 的整数数组 height 。有 n 条垂线，第 i 条线的两个端点是 (i, 0) 和 (i, height[i])。<br>找出其中的两条线，使得它们与 x 轴共同构成的容器可以容纳最多的水。返回容器可以储存的最大水量。<br>说明：你不能倾斜容器。</p>
<p>解：<strong>双指针</strong>，相对更短的一侧向内移动，面积可能变小、不变、变大，但是相对更长的一侧向内移动，面积只会变小、不变。</p>
<ol>
<li>记录在最左右两边的盛水面积。</li>
<li>将左右指针中相对较短的一侧向中间移动一格，计算面积，并于记录值比较取更大的值。</li>
<li>重复2，直到左右指针重合，输出最大值。</li>
</ol>
<figure class="highlight java"><table><tr><td class="gutter hljs"><div class="hljs code-wrapper"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></div></td><td class="code"><div class="hljs code-wrapper"><pre><code class="hljs Java"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Solution</span> </span>&#123;<br>    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">int</span> <span class="hljs-title">maxArea</span><span class="hljs-params">(<span class="hljs-keyword">int</span>[] height)</span> </span>&#123;<br>        <span class="hljs-keyword">int</span> n = height.length;<br>        <span class="hljs-keyword">int</span> l = <span class="hljs-number">0</span>, r = n - <span class="hljs-number">1</span>;<br>        <span class="hljs-keyword">int</span> max = Math.min(height[l], height[r]) * (r - l);<br>        <span class="hljs-keyword">while</span> (l &lt; r) &#123;<br>            <span class="hljs-keyword">if</span> (height[l] &gt; height[r]) &#123;<br>                --r;<br>            &#125;<br>            <span class="hljs-keyword">else</span> &#123;<br>                ++l;<br>            &#125;<br>            max = Math.max(max, Math.min(height[l], height[r]) * (r - l));<br>        &#125;<br>        <span class="hljs-keyword">return</span> max;<br>    &#125;<br>&#125;<br></code></pre></div></td></tr></table></figure>

<hr>
<h4 id="LC15-三数之和-M"><a href="#LC15-三数之和-M" class="headerlink" title="LC15 三数之和 M"></a>LC15 三数之和 M</h4><p>描述：给你一个包含 n 个整数的数组 nums，判断 nums 中是否存在三个元素 a，b，c ，使得 a + b + c = 0 ？请你找出所有和为 0 且不重复的三元组。<br>注意：答案中不可以包含重复的三元组。</p>
<p>解：<strong>排序 + 双指针</strong>。</p>
<ol>
<li>将数组从小到大排序。</li>
<li>i 遍历数组，如果nums[i] 大于 0，三数之和一定大于0，return 结束。</li>
<li>j 为 i 后一位，k 为数组最后一位。<ul>
<li>三数之和大于 0，–k；</li>
<li>三数之和小于 0，++j；</li>
<li>三数之和等于 0，将三个数加入 List；<br>i 为当前位置时，可能还有不同且符合要求的 j、k 组合，因此确保 nums[j - 1] != nums[j] ，++j，k不变。</li>
</ul>
</li>
<li>确保 nums[i - 1] != nums[i] ，++i，j = i + 1，k = nums.length - 1。</li>
</ol>
<figure class="highlight java"><table><tr><td class="gutter hljs"><div class="hljs code-wrapper"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br></pre></div></td><td class="code"><div class="hljs code-wrapper"><pre><code class="hljs java"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Solution</span> </span>&#123;<br>    <span class="hljs-keyword">public</span> List&lt;List&lt;Integer&gt;&gt; threeSum(<span class="hljs-keyword">int</span>[] nums) &#123;<br><br>        List&lt;List&lt;Integer&gt;&gt; result = <span class="hljs-keyword">new</span> ArrayList&lt;&gt;();<br><br>        <span class="hljs-keyword">if</span> (nums.length &lt; <span class="hljs-number">3</span>) &#123;<br>            <span class="hljs-keyword">return</span> result;<br>        &#125;<br><br>        Arrays.sort(nums);<br><br>        <span class="hljs-keyword">for</span> (<span class="hljs-keyword">int</span> i = <span class="hljs-number">0</span>; i &lt; nums.length - <span class="hljs-number">2</span>;) &#123;<br>            <span class="hljs-keyword">if</span> (nums[i] &gt; <span class="hljs-number">0</span>) &#123;<br>                <span class="hljs-keyword">return</span> result;<br>            &#125;<br>            <span class="hljs-keyword">int</span> j = i + <span class="hljs-number">1</span>, k = nums.length - <span class="hljs-number">1</span>;<br>            <span class="hljs-keyword">while</span> (j &lt; k) &#123;<br>                <span class="hljs-keyword">if</span> (nums[i] + nums[j] + nums[k] == <span class="hljs-number">0</span>) &#123;<br>                    List&lt;Integer&gt; list = <span class="hljs-keyword">new</span> ArrayList&lt;&gt;();<br>                    list.add(nums[i]);<br>                    list.add(nums[j]);<br>                    list.add(nums[k]);<br>                    result.add(list);<br>                    ++j;<br>                    <span class="hljs-keyword">while</span> (j &lt; nums.length - <span class="hljs-number">1</span> &amp;&amp; nums[j - <span class="hljs-number">1</span>] == nums[j]) &#123;<br>                        ++j;<br>                    &#125;<br>                &#125;<br>                <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> (nums[i] + nums[j] + nums[k] &gt; <span class="hljs-number">0</span>) &#123;<br>                    --k;<br>                &#125;<br>                <span class="hljs-keyword">else</span> &#123;<br>                    ++j;<br>                &#125;<br>            &#125;<br>            ++i;<br>            <span class="hljs-keyword">while</span> (i &lt; nums.length - <span class="hljs-number">2</span> &amp;&amp; nums[i - <span class="hljs-number">1</span>] == nums[i]) &#123;<br>                ++i;<br>            &#125;<br>        &#125;<br><br>        <span class="hljs-keyword">return</span> result;<br>    &#125;<br>&#125;<br></code></pre></div></td></tr></table></figure>


            </div>
            <hr>
            <div>
              <div class="post-metas mb-3">
                
                  <div class="post-meta mr-3">
                    <i class="iconfont icon-category"></i>
                    
                      <a class="hover-with-bg" href="/categories/%E7%AE%97%E6%B3%95/">算法</a>
                    
                  </div>
                
                
                  <div class="post-meta">
                    <i class="iconfont icon-tags"></i>
                    
                      <a class="hover-with-bg" href="/tags/%E5%8A%A8%E6%80%81%E8%A7%84%E5%88%92/">动态规划</a>
                    
                  </div>
                
              </div>
              
                <p class="note note-warning">
                  
                    本博客所有文章未经允许，严禁转载！
                  
                </p>
              
              
                <div class="post-prevnext">
                  <article class="post-prev col-6">
                    
                    
                      <a href="/2022/03/21/%E7%AE%97%E6%B3%95-%E5%85%B6%E4%BB%96%E7%AE%97%E6%B3%95/">
                        <i class="iconfont icon-arrowleft"></i>
                        <span class="hidden-mobile">算法 --- 其他算法</span>
                        <span class="visible-mobile">上一篇</span>
                      </a>
                    
                  </article>
                  <article class="post-next col-6">
                    
                    
                      <a href="/2022/03/21/Java%E5%9F%BA%E7%A1%80/">
                        <span class="hidden-mobile">Java基础</span>
                        <span class="visible-mobile">下一篇</span>
                        <i class="iconfont icon-arrowright"></i>
                      </a>
                    
                  </article>
                </div>
              
            </div>

            
          </article>
        </div>
      </div>
    </div>
    
      <div class="d-none d-lg-block col-lg-2 toc-container" id="toc-ctn">
        <div id="toc">
  <p class="toc-header"><i class="iconfont icon-list"></i>&nbsp;目录</p>
  <div class="toc-body" id="toc-body"></div>
</div>

      </div>
    
  </div>
</div>

<!-- Custom -->


    

    
      <a id="scroll-top-button" aria-label="TOP" href="#" role="button">
        <i class="iconfont icon-arrowup" aria-hidden="true"></i>
      </a>
    

    
      <div class="modal fade" id="modalSearch" tabindex="-1" role="dialog" aria-labelledby="ModalLabel"
     aria-hidden="true">
  <div class="modal-dialog modal-dialog-scrollable modal-lg" role="document">
    <div class="modal-content">
      <div class="modal-header text-center">
        <h4 class="modal-title w-100 font-weight-bold">搜索</h4>
        <button type="button" id="local-search-close" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body mx-3">
        <div class="md-form mb-5">
          <input type="text" id="local-search-input" class="form-control validate">
          <label data-error="x" data-success="v"
                 for="local-search-input">关键词</label>
        </div>
        <div class="list-group" id="local-search-result"></div>
      </div>
    </div>
  </div>
</div>
    

    
  </main>

  <footer class="text-center mt-5 py-3">
  <div class="footer-content">
     CC <i class="iconfont icon-love"></i> XX
  </div>
  
  <div class="statistics">
    
    

    
      
        <!-- 不蒜子统计PV -->
        <span id="busuanzi_container_site_pv" style="display: none">
            总访问量 
            <span id="busuanzi_value_site_pv"></span>
             次
          </span>
      
      
        <!-- 不蒜子统计UV -->
        <span id="busuanzi_container_site_uv" style="display: none">
            总访客数 
            <span id="busuanzi_value_site_uv"></span>
             人
          </span>
      
    
  </div>


  

  
</footer>


  <!-- SCRIPTS -->
  
  <script  src="https://cdn.jsdelivr.net/npm/nprogress@0/nprogress.min.js" ></script>
  <link  rel="stylesheet" href="https://cdn.jsdelivr.net/npm/nprogress@0/nprogress.min.css" />

  <script>
    NProgress.configure({"showSpinner":false,"trickleSpeed":100})
    NProgress.start()
    window.addEventListener('load', function() {
      NProgress.done();
    })
  </script>


<script  src="https://cdn.jsdelivr.net/npm/jquery@3/dist/jquery.min.js" ></script>
<script  src="https://cdn.jsdelivr.net/npm/bootstrap@4/dist/js/bootstrap.min.js" ></script>
<script  src="/js/events.js" ></script>
<script  src="/js/plugins.js" ></script>

<!-- Plugins -->


  <script  src="/js/local-search.js" ></script>



  
    
      <script  src="/js/img-lazyload.js" ></script>
    
  



  



  
    <script  src="https://cdn.jsdelivr.net/npm/tocbot@4/dist/tocbot.min.js" ></script>
  
  
    <script  src="https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@3/dist/jquery.fancybox.min.js" ></script>
  
  
    <script  src="https://cdn.jsdelivr.net/npm/anchor-js@4/anchor.min.js" ></script>
  
  
    <script defer src="https://cdn.jsdelivr.net/npm/clipboard@2/dist/clipboard.min.js" ></script>
  



  <script defer src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js" ></script>




  <script  src="https://cdn.jsdelivr.net/npm/typed.js@2/lib/typed.min.js" ></script>
  <script>
    (function (window, document) {
      var typing = Fluid.plugins.typing;
      var title = document.getElementById('subtitle').title;
      
        typing(title);
      
    })(window, document);
  </script>















<!-- 主题的启动项 保持在最底部 -->
<script  src="/js/boot.js" ></script>


</body>
</html>
